package middlewares

import (
	"Gin-Gorm-boke/boke_common/HttpCode"
	"Gin-Gorm-boke/boke_common/helper"
	"Gin-Gorm-boke/boke_common/models"
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"strconv"
)

func AuthUserCheck() gin.HandlerFunc {
	return func(c *gin.Context) {
		auth := c.GetHeader("token")
		fmt.Println("auth:", auth)
		userClaim, err := helper.AnalysisToken(auth)
		if err != nil || userClaim == nil {
			fmt.Println("校验出错")
			c.Abort()
			c.JSON(200, gin.H{
				"code": HttpCode.SYSTEM_ERROR,
				"msg":  "认证或授权失败",
			})
			return

		}
		fmt.Println("userId", userClaim.UserId)
		c.Set("userId", userClaim.UserId)
		err = models.RDb.Get(context.Background(), "bloglogin:"+strconv.Itoa(userClaim.UserId)).Err()
		if err != nil {
			c.JSON(401, gin.H{
				"code": HttpCode.NEED_LOGIN,
				"msg":  HttpCode.AppHttpCodeEnumMsg[HttpCode.NEED_LOGIN],
			})
			c.Abort()
			return
		}
		c.Next()

	}
}
